package com.zjpavt.taiyuan.controller.base;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.NamedThreadLocal;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description: 用于拦截所有请求记录，并打印出请求总时间
 * @Author: wy
 * @Date: Created in 9:21 2018/5/24
 */
@Component
public class RequestLogInterceptor extends HandlerInterceptorAdapter {

    private static final Logger logger = LoggerFactory.getLogger(RequestLogInterceptor.class);

    //线程绑定变量，提供线程局部变量
    private NamedThreadLocal<Long> startTimeThreadLocal =
            new NamedThreadLocal<>("RequestMonitoring_StartTime");

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        long beginTime = System.currentTimeMillis();
        startTimeThreadLocal.set(beginTime);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response,
                                Object handler, Exception ex) throws Exception {
        long endTime = System.currentTimeMillis();
        long beginTime = startTimeThreadLocal.get();

        long consumeTime = endTime - beginTime;
        //响应头支持跨域操作
	    response.setHeader("Access-Control-Allow-Origin", "*");
	    String url = request.getRequestURI()
                .replace(request.getContextPath(),"");
        String ipAddress = request.getRemoteAddr();
        String requestMethod = request.getMethod();
        String loggerInfo = "ip is :"+ipAddress +
                ", request for uri :"+url +
                ", requestMethod is : "+requestMethod +
                ", request waste of time : "+consumeTime+" ms";

        logger.info(loggerInfo);
    }
}
